package com.kfm.servlet;

import com.kfm.db.DBUtils;
import com.kfm.model.AccountModel;
import com.wf.captcha.utils.CaptchaUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求参数
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        String confirmPassword = req.getParameter("confirm_password");
        String captcha = req.getParameter("verification_code");
        String name = req.getParameter("name");

        // 验证码校验
        if (!CaptchaUtil.ver(captcha, req)){
            // 验证码错误
            req.setAttribute("msg", "验证码错误");
            req.getRequestDispatcher("register.jsp").forward(req, resp);
            return;
        }

        // 验证码正确, 清除验证码
        CaptchaUtil.clear(req);

        // 验证密码
        if (!password.equals(confirmPassword)){
            req.setAttribute("msg", "两次密码不一致");
            req.getRequestDispatcher("register.jsp").forward(req, resp);
            return;
        }

        // 验证用户是否已存在
        String sql = "select * from account where phone = ?";

        DBUtils<AccountModel> dbUtils = new DBUtils<>(1);

        List<AccountModel> select = dbUtils.select(sql, AccountModel.class, phone);

        if (select.size() > 0){
            req.setAttribute("msg", "用户已存在");
            req.getRequestDispatcher("register.jsp").forward(req, resp);
            return;
        }

        // 保存用户信息
        sql = "insert into account (phone, password, name, type) values (?, ?, ?, ?)";

        int i = dbUtils.update(sql, phone, password, name, 1);

        if (i > 0){
            // 注册成功, 重定向到登录
            req.getSession().setAttribute("msg", "注册成功");
            resp.sendRedirect("login");
        } else {
            // 注册失败
            req.setAttribute("msg", "注册失败, 请重试");
            req.getRequestDispatcher("register.jsp").forward(req, resp);
        }
    }
}
